package com.fqgj.xjd.user.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.xjd.user.dao.UserAppListDao;
import com.fqgj.xjd.user.dao.UserBehaviorDeviceShumeiDao;
import com.fqgj.xjd.user.entity.UserAppListEntity;
import com.fqgj.xjd.user.entity.UserBehaviorDeviceShumeiEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author moss
 * 2019-04-25
 */
@SuppressWarnings("ALL")
@Component
public class AppListTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppListTask.class);
    private ThreadPoolExecutor executorService = new ThreadPoolExecutor(10,20,5, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
    @Autowired
    UserAppListDao userAppListDao;

    @Autowired
    UserBehaviorDeviceShumeiDao userBehaviorDeviceShumeiDao;

    private LongAdder longAdder = new LongAdder();


    public void batchExecute(long startId, int page) throws InterruptedException {
        final AtomicInteger totalCrawled = new AtomicInteger(0);
        while (true) {
            //查找未进行 appList解析的数据
            List<UserBehaviorDeviceShumeiEntity> userBehaviorDeviceShumeiEntities = userBehaviorDeviceShumeiDao.selectNeedParseAppListDateByPage(startId, page);
            LOGGER.info("=======执行 APP解析 任务=========startId:{}, page:{},size:{}", startId, page,userBehaviorDeviceShumeiEntities.size());
            for (UserBehaviorDeviceShumeiEntity userBehaviorDeviceShumeiEntity : userBehaviorDeviceShumeiEntities) {
                executorService.execute(() -> {
                    try {
                        //获取 OSS连接
                        String url = userBehaviorDeviceShumeiEntity.getFingerprintInfoUrl();
                        if (StringUtils.isEmpty(url)) {
                            return;
                        }
                        //换成内网oss,不然请求会有一定资费产生
                        url = url.replace("cashmama-oss-pro.cashmama.in", "cashmama-pro.oss-ap-south-1-internal.aliyuncs.com");
                        url = url.replace("cashmama-fat.oss-ap-south-1.aliyuncs.com", "cashmama-fat.oss-ap-south-1-internal.aliyuncs.com");
                        longAdder.increment();
                        LOGGER.info("======请求的url====={},执行的ID:{},任务数:{}", url, userBehaviorDeviceShumeiEntity.getId(), longAdder.intValue());
                        //获取  JSON 解析
                        String data = HttpUtil.getPage(url);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONArray apps = jsonObject.getJSONArray("apps");
                        if (apps == null) {
                            return;
                        }
                        LOGGER.info("======APP数量====={}", apps.size());
                        for (Object app : apps) {
                            try {
                                String[] split = ((String) app).split(",");
                                UserAppListEntity userAppListEntity = new UserAppListEntity();
                                userAppListEntity.setUserCode(userBehaviorDeviceShumeiEntity.getUserCode());
                                userAppListEntity.setAppInstallTime(new Date(Long.valueOf(split[0])));
                                userAppListEntity.setAppPackageName(split[1]);
                                userAppListEntity.setAppName(split[2]);
                                try {
                                    userAppListEntity.setNonSystemApp(Integer.valueOf(split[3]));
                                } catch (NumberFormatException e) {
                                    userAppListEntity.setNonSystemApp(1);
                                }
                                //入库
                                userAppListDao.insert(userAppListEntity);
                                LOGGER.info("======入库成功======");
                            } catch (Exception e) {
                                LOGGER.info("======入库失败======");
                            }

                        }
                    } catch (Exception e) {
                        LOGGER.info("======此条数据无效======");
                    }

                });
            }

            if (userBehaviorDeviceShumeiEntities.size() != page) {
                break;

            }else {
                startId = userBehaviorDeviceShumeiEntities.get(userBehaviorDeviceShumeiEntities.size() - 1).getId();
            }

            while (true) {//防止队列撑爆
                LOGGER.info("other queue size: {}, other active thread:{}, other total message: {}", executorService.getQueue().size(), executorService.getActiveCount(), totalCrawled.intValue());
                if (executorService.getQueue().size() < 2000) {
                    break;
                } else {
                    LOGGER.info("borrowBillMsgExecutor.getQueue().size()>1000, sleep:", executorService.getQueue().size(), executorService.getActiveCount(), totalCrawled.intValue());
                    Thread.sleep(1000);
                }
            }
        }
        LOGGER.info("=======执行 APP解析 任务end=========");

    }

}
